var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var { expressjwt: jwt } = require("express-jwt");
var md5 = require('md5')
const { ForbiddenError, ServiceError } = require("./utils/errors")
const session = require('express-session')

// var indexRouter = require('./routes/index');
// var usersRouter = require('./routes/users');

// 默认读取项目根目录下的 .env 中的环境变量
require('dotenv').config()
require('express-async-errors')
// 引入连接数据库文件
require('./dao/db')

// 引入路由
var adminRouter = require('./routes/admin')
var captcha = require('./routes/acptcha')
var bannerRouter = require('./routes/banner')

// 创建服务器实例
var app = express();
// 配置session中间件，用来存储验证码
app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: true,
  saveUninitialized: true,
}))

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 配置验证 token 接口
app.use(jwt({
  secret: md5(process.env.JWT_SECRET), // 生成token时的密钥
  algorithms: ['HS256'] // 加密算法
}).unless({
  // 需要排除验证token的路由
  path: ["/api/admin/login", "/res/captcha"] 
}))

// 使用路由中间件
app.use('/res/captcha', captcha)
app.use('/api/admin', adminRouter);
app.use('/api/banner', bannerRouter)


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // token失效时，返回相应错误
  console.log('err.name', err.name)
  console.log('err.message', err.message)
  if(err.name === 'UnauthorizedError') {
    res.send(new ForbiddenError('未登录或登录已过期').toResponseJSON())
  }else if(err instanceof ServiceError) {
    res.send(err.toResponseJSON())
  }else {
    res.send(new UnknownError().toResponseJSON())
  }
});

module.exports = app;
